package ru.bytedog.artifact.cache.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ru.bytedog.artifact.cache.dto.CacheInfo;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CacheService {

    private static final Cache<String, byte[]> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    public void add(MultipartFile file, String id) throws IOException {
        log.info("File uploaded: {} with id: {} and size: {}", file.getOriginalFilename(), id, file.getSize());
        cache.put(id, file.getBytes());
    }

    public Optional<byte[]> get(String id) {
        log.info("Download file by id: {}", id);
        Optional<byte[]> file = Optional.ofNullable(cache.getIfPresent(id));
        if (file.isEmpty()) {
            log.info("File not found");
            return file;
        }
        log.info("File found");
        return file;
    }


    public void clear() {
        log.info("Clear cache");
        cache.cleanUp();
    }

    public CacheInfo getCacheInfo() {
        CacheInfo cacheInfo = new CacheInfo(cache.size(), cache.asMap().values().stream()
                .mapToLong(file -> file.length)
                .sum());
        log.info("Cache info: {}", cacheInfo);
        return cacheInfo;
    }

}
